from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from django.conf import settings
import os
import uuid
from .models import ArticleModel
from .forms import ArticleForm


class IndexView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'index.html')

    def post(self, request, *args, **kwargs):
        file = request.FILES.get('file')
        if file:
            filename = str(uuid.uuid4()) + os.path.splitext(file.name)[1]
            outpath = os.path.join(settings.BASE_DIR, 'static', filename)
            with open(outpath, 'wb') as fp:
                for chunk in file.chunks():
                    fp.write(chunk)
            # return HttpResponse('文件上传成功')
            return HttpResponse(content='<a href="/static/%s">%s</a>' % (filename, filename), content_type='text/html')
        else:
            return HttpResponse('文件不能为空')


class FileFormView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'formfile.html')

    # def post(self, request, *args, **kwargs):
    #     title = request.POST.get('title')
    #     content = request.POST.get('content')
    #     thumbnail = request.FILES.get('thumbnail')
    #     article = ArticleModel(title=title, content=content, thumbnail=thumbnail)
    #     article.save()
    #     return HttpResponse('success')

    # TODO: 【Django文件上传】限制上传的文件拓展名
    # TODO: 上传图片
    def post(self, request, *args, **kwargs):
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('success')
        else:
            print(form.errors.get_json_data())
            return HttpResponse('fail')
